import os, urllib
from datetime import datetime
from rer import kwargs, Categories
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class EditData(webapp.RequestHandler):
    @kwargs
    def post(self, action, pattern, title, description, category, key):
        if self.request.uri.find(self.get_url()) == -1:
            self.redirect('/')
        
        data = db.get(db.Key(key))
        if not data:
            self.redirect('/reference')
        
        if action and action == "Delete":
            data.delete()
        else:
            if (data.title,
                data.pattern,
                data.description,
                data.category) != (title,pattern,description,category):
                if(data.title != title):
                    data.title = title
                
                if(data.pattern != pattern):
                    data.pattern = pattern
                
                if(data.description != description):
                    data.description = description
                
                if(data.category != category):
                    data.category = db.get(db.Key(category))
                
                data.last_update = datetime.now()
                data.put()
        
        current = db.get(db.Key(category))
        params = ('?cr=' + urllib.quote(current.en)) if current else ''
        self.redirect('/reference' + params)
        return
    
    @kwargs
    def get(self, key):
        data = db.get(db.Key(key))
        if not data:
            self.redirect('/reference')
        
        res = {'sub_title': 'Update SampleData',
               'categories': Categories.all(),
               'data': data}
        path = os.path.join(os.path.dirname(__file__), 'template', 'update.sampledata.html')
        self.response.out.write(template.render(path, res))


application = webapp.WSGIApplication([('/update_sampledata', EditData)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()